package dao;





import org.junit.Test;
import pojo.Photo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static util.DBUtil.getConnection;

public class PhotoDaoImpl implements PhotoDao {
    @Override
    public boolean savePhoto(Photo photo) {
        Connection conn=getConnection();
//        在对应post表中添加id，是图片和
        String sql="insert into photo(value,post_id) values (?,?)";
        int result=0;
        try{
            PreparedStatement sta=conn.prepareStatement(sql);
//            sta.setInt(1,photo.getPhotoId());
            sta.setString(2,photo.getValue());
            sta.setInt(3,photo.getPostId());
            result=sta.executeUpdate();
        }catch (SQLException e){
            System.out.println("PhotoDaoImpl.savePhoto():数据库操作异常");
        }
        return result==1;
    }

    @Override
    public List<Photo> getPhoto(int postId) {
        Connection conn=getConnection();
//        在对应post表中添加id，是图片和
        String sql="select * from photo where post_id=?";
        List<Photo> list=new ArrayList<>();
        try{
            PreparedStatement sta=conn.prepareStatement(sql);
            sta.setInt(1,postId);
            ResultSet resultSet=sta.executeQuery();
            while (resultSet.next()) {
                Photo photo=new Photo();
                photo.setPhotoId(resultSet.getInt("photo_id"));
                photo.setPostId(resultSet.getInt("post_id"));
                photo.setValue(resultSet.getString("value"));
                list.add(photo);
            }
        }catch (SQLException e){
            System.out.println("PhotoDaoImpl.getPhoto():数据库操作异常");
        }
        return list;
    }

    @Override
    public boolean delPhoto(int photoId) {
        Connection conn=getConnection();
//        在对应post表中添加id，是图片和
        String sql="delete from photo where photo_id=?";
        int result=0;
        try{
            PreparedStatement sta=conn.prepareStatement(sql);
            sta.setInt(1,photoId);
            result=sta.executeUpdate();
        }catch (SQLException e){
            System.out.println("PhotoDaoImpl.delPhoto():数据库操作异常");
        }
        return result==1;
    }

    @Test
    public void test(){
//        Photo photo=new Photo();
//        photo.setValue("2223");
//        photo.setPostId(2409);
//        savePhoto(photo);


//        List<Photo> photos=getPhoto(2409);
//        System.out.println(photos.toString());


//        delPhoto(1);
    }
}
